package com.mmall.controller;

import com.mmall.model.SysUser;
import com.mmall.service.SysUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by asus on 2018/4/1.
 */
@Controller
public class UserController {

    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            //获取用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //根据用户名得到用户
            SysUser user = sysUserService.findByKeyword(username);
            //向登录页展示错误信息
            String errorMsg = "";
            //获取转发等信息
            String ret = request.getParameter("ret");
            //对用户输入信息进行校验
            if(StringUtils.isBlank(username)){
                errorMsg = "用户名不能为空";
            }else if(StringUtils.isBlank(password)){
                errorMsg = "密码不能为空";
            }else if(user == null){
                errorMsg = "查询不到指定的用户";
            }else if(!MD5Util.encrypt(password).equals(user.getPassword())){
                errorMsg = "用户名或密码输入有误";
            }else if(user.getStatus()!=1){
                errorMsg = "用户账号已冻结无法登陆";
            }else{
                request.getSession().setAttribute("user",user);
                //转发
                if(StringUtils.isNotBlank(ret)){
                    response.sendRedirect(ret);
                    return;
                }else{
                    //正常登陆
                    response.sendRedirect("/admin/index.page");
                    return;
                }
            }

            //校验后无法正常登陆，重新转发到登录页
            request.setAttribute("error",errorMsg);
            request.setAttribute("username",username);
            if(StringUtils.isNotBlank(ret)){
                request.setAttribute("ret",ret);
            }
            String path = "signin.jsp";
            request.getRequestDispatcher(path).forward(request,response);
            return;
        }

        @RequestMapping("/logout.page")
        public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
            request.getSession().invalidate();
            String path = "signin.jsp";
            response.sendRedirect(path);
    }
}
